<?php
// +----------------------------------------------------------------------
// | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
// +----------------------------------------------------------------------
// | File name: LoanApply.php
// +----------------------------------------------------------------------
// | Author: liuju
// +----------------------------------------------------------------------
// | Description: 描述文档功能
// +----------------------------------------------------------------------
// | Others: 其他内容的说明
// +----------------------------------------------------------------------
// | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
// +----------------------------------------------------------------------
// | 1.Date: 2019-02-28 Author: liuju Modification: 创建
// +----------------------------------------------------------------------

namespace App\ModelTransfers\Traits;


use App\Facades\MoneyPlatformRequestFacade;
use App\Models\LoanApply;
use App\Models\SettingChannel;
use App\Models\SettingRepayRate;
use App\Models\UserBankCard;
use App\Models\UserGlobal;
use App\Models\UserLoanRequest;
use App\ModelTransfers\Base;
use App\ModelTransfers\WsFund\ApiLog;
use App\ModelTransfers\WsFund\WsFund;
use App\ModelTransfers\WsLoans\LoanApprove;
use App\ModelTransfers\WsLoans\LoanOrder;
use App\ModelTransfers\WsLoans\LoanProductTerm;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

trait LoanApplyTrait
{

    static $map=[];
    /**
     * Description:移除迁移放款数据
     * Author: liuju
     * DateTime: 2019-03-05 17:30
     * @param $userId
     * @return bool|int|null
     * @throws \Exception
     */
    public static function removeTransfer($userId = '')
    {
        return LoanApply::whereNotNull('trans_id')
            ->when($userId,function($query) use($userId){
                return $query->where('user_id',$userId);
            })
            ->delete();
    }

    public static function transfer($transList, $user, $userId, $term)
    {
        $transIdList = LoanApply::where('user_id',$userId)->pluck('trans_id')->toArray();
        $list1 = self::one($transList, $user, $userId, $term,$transIdList);
        $list2 = self::two($transList, $user, $userId, $term,$transIdList);
        $list3 = self::three($transList, $user, $userId, $term,$transIdList);
        $list4 = self::oldGd($transList, $user, $userId, $term,$transIdList);
        if(self::$map){
            $status = 0;
            if(self::$map['status'] == LoanApply::LOAN_STATUS_SUCCESS){
                $status = UserGlobal::STATUS_REPAY_INIT;
            }
            if(self::$map['status'] == LoanApply::LOAN_STATUS_FAIL){
                $status = UserGlobal::STATUS_LOAN_MONEY_FAIL;
            }
            if(UserGlobal::where('uid',$userId)->value('uid')){
                UserGlobal::where('uid',$userId)->update(['global_status'=>$status]);
            }else{
                UserGlobal::create([
                    'uid'=>$userId,
                    'global_status' => $status,
                ]);
            }
        }
        $data =  array_unique(array_merge($list1, $list2, $list3,$list4));
        return $data;
    }


    /**
     * Description:晋商相关数据
     * Author: liuju
     * DateTime: 2019-03-12 13:59
     * @param $transList
     * @param $user
     * @param $userId
     * @param $term
     * @param $transIdList
     * @return bool
     */
    public static function one($transList, $user, $userId, $term,$transIdList)
    {
        $list = [];
        $data = DB::connection('transfer')->select("
        select 
       c.product_code,
       c.loan_channel,
       c.id  as trans_id,
       a.loan_amount  as  amount ,
       (a.loan_amount  - ifnull(a.user_premium,0)) as    arrival_account ,
       ifnull(a.user_premium,0) as  pre_insurance_amt ,
       a.loan_term as period,
       a.apply_id as  out_trade_id,
       (case status when 120 then  0 when 121 then  1 when 122 then 2 when 123 then 3 end) as  loan_status ,
       DATE_FORMAT(b.loan_time,'%Y-%m-%d %H:%i:%s') as loan_time ,
       DATE_FORMAT(a.create_time,'%Y-%m-%d %H:%i:%s') as created_at ,
       DATE_FORMAT(a.update_time,'%Y-%m-%d %H:%i:%s') as updated_at ,
      (select bank_card_no from  ws_account.account_user_card where id = c.loan_card_id ) as card_no,
      c.ip,
      c.apply_rate as lending_rate,
      a.channel_loan_id as loan_id
from ws_fund.uni_fund_order a,
     ws_loan.loan_order b,
     ws_loan.loan_apply c
 where a.apply_id = b.apply_id 
 and a.status  in (120,121,123,122)
 and c.id = b.apply_id
 and b.is_valid = 1
 and c.loan_channel ='LCC201709190010'  and c.phone='" . $user->phone . "'
        ");
        $applyIdList = array_pluck($data, 'trans_id');
        $log = $applyIdList ? ApiLog::getResponse($applyIdList)->get()->toArray() : [];
        $moneyList = [];
        foreach ($log as $k => $value) {
            $key = $value['order_id'];
            $value = json_decode($value['response'], true);
            $moneyList[$key] = $value['data']['transMoneyList'];
        }
        foreach ($data as $key => $item) {
            $item = (array)$item;
            if(in_array($item['trans_id'],$transIdList)){
                continue;
            }
            if(!self::$map){
                self::$map = [
                    'time'=> $item['created_at'],
                    'status'=>$item['loan_status']
                ];
            }
            if(self::$map && str_replace(['-',':'],'',$item['created_at']) > str_replace(['-',':'],'',self::$map['time'])){
              self::$map['status'] = $item['loan_status'];
            }

            foreach ($term as $info) {
                if ($info->product_code === $item['product_code'] && $info->loan_channel == $item['loan_channel'] && $info->term_no == $item['period']) {
                    $item['manage_rate'] = bcdiv(round($info->service_rate, 2), 100, 4);
                }
            }

            $item['loan_request_id'] = !empty($transList[$item['trans_id']]) ? $transList[$item['trans_id']] : '';
            $item['loan_request_id'] && self::updateLoanRequest($item['loan_request_id']);

            $item['insurance_rate'] = bcdiv($item['pre_insurance_amt'], $item['amount'], 4);
            $item['lending_rate'] = bcdiv($item['lending_rate'], 100, 4);
            $item['fines_rate'] = 0.0030;
            $rate = SettingRepayRate::getRateByChannl('JCFC', $item['period']);
            $item['month_insurance_rate'] = $rate['month_insurance_rate'];
            $item['repayment_rate'] = $rate['repayment_rate'];
            $item['user_id'] = $userId;
            empty($item['loan_id']) && $item['loan_id'] = 0;
            $item['trans_money_list'] = !empty($moneyList[$item['out_trade_id']]) ? $moneyList[$item['out_trade_id']] : '';
            if ($item['trans_money_list']) {
                foreach ($item['trans_money_list'] as $k1 => $v1) {
                    if ($v1['transType'] === '01') {
                        $item['pre_insurance_amt'] = $v1['transAmt'];
                    }
                    if ($v1['transType'] === '02') {
                        $item['performance_insurance'] = $v1['transAmt'];
                    }
                    if ($v1['transType'] === '03') {
                        $item['arrival_account'] = $v1['transAmt'];
                    }
                }
            }
            $item['bank_card_id'] = UserBankCard::where(['card_num' => $item['card_no']])->value('id') ?: 0;
            unset($item['card_no'], $item['product_code'], $item['loan_channel']);
            if(self::check($item['trans_id'])){
                continue;
            }else{
                $apply =LoanApply::create($item);
                if($item['loan_status'] == LoanApply::LOAN_STATUS_SUCCESS){
                    $list[] = $apply;
                }
            }
        }

        return $list ;
    }


    public static function two($transList, $user, $userId, $term,$transIdList)
    {
        $list = [];
        $data = DB::connection('transfer')->select("
        select 
       c.user_id,
       c.id as trans_id,
       c.product_code,
       c.loan_channel,
       d.approve_amount as  amount ,
       (d.approve_amount  - ifnull(c.premium_amount,0)) as   arrival_account ,
       ifnull(c.premium_amount,0) as pre_insurance_amt ,
       c.apply_term as  period,
      c.id as out_trade_id,
    (case  when c.apply_status = '7' or c.apply_status = '8' or c.apply_status='9' then 
              2
    when c.apply_status='10' then 
           3
    end ) as loan_status ,
    DATE_FORMAT(b.loan_time,'%Y-%m-%d %H:%i:%s') as loan_time ,
    DATE_FORMAT(c.create_time,'%Y-%m-%d %H:%i:%s') as created_at ,
    DATE_FORMAT(c.update_time,'%Y-%m-%d %H:%i:%s') as  updated_at ,
    (select bank_card_no from  ws_account.account_user_card where id = c.loan_card_id ) as card_no,
    c.ip,
    c.apply_rate as  lending_rate
from ws_loan.loan_order b,
   ws_loan.loan_apply c,
   ws_loan.loan_approve d
 where  c.id = b.apply_id
 and c.id = d.id
 and d.is_valid = 1
 and b.is_valid = 1
 and b.order_status = '2'
 and c.apply_status in ('7','8','9','10')
 and c.phone='" . $user->phone . "'
        ");

        $applyIdList = array_pluck($data, 'trans_id');
        $log = $applyIdList ? ApiLog::getResponse($applyIdList)->get()->toArray() : [];
        $moneyList = [];
        foreach ($log as $k => $value) {
            $key = $value['order_id'];
            $value = json_decode($value['response'], true);
            $moneyList[$key] = $value['data']['transMoneyList'];
        }
        foreach ($data as $item) {
            $item = (array)$item;
            $item = (array)$item;
            if(in_array($item['trans_id'],$transIdList)){
                continue;
            }
            if(!self::$map){
                self::$map = [
                    'time'=> $item['created_at'],
                    'status'=>$item['loan_status']
                ];
            }
            if(self::$map && str_replace(['-',':'],'',$item['created_at'])){
                self::$map['status'] = $item['loan_status'];
            }
            foreach ($term as $info) {
                if ($info->product_code === $item['product_code'] && $info->loan_channel == $item['loan_channel'] && $info->term_no == $item['period']) {
                    $item['manage_rate'] = bcdiv(round($info->service_rate, 2), 100, 4);
                }
            }

            $item['amount'] = bcdiv($item['amount'], 100, 2);
            $item['arrival_account'] = bcdiv($item['arrival_account'], 100, 2);
            $item['pre_insurance_amt'] = bcdiv($item['pre_insurance_amt'], 100, 2);

            $item['trans_money_list'] = !empty($moneyList[$item['out_trade_id']]) ? $moneyList[$item['out_trade_id']] : '';
            if ($item['trans_money_list']) {
                foreach ($item['trans_money_list'] as $k1 => $v1) {
                    if ($v1['transType'] === '01') {
                        $item['pre_insurance_amt'] = $v1['transAmt'];
                    }
                    if ($v1['transType'] === '02') {
                        $item['performance_insurance'] = $v1['transAmt'];
                    }
                    if ($v1['transType'] === '03') {
                        $item['arrival_account'] = $v1['transAmt'];
                    }
                }
            }
            $item['loan_request_id'] = !empty($transList[$item['trans_id']]) ? $transList[$item['trans_id']] : '';

            $item['loan_request_id'] && self::updateLoanRequest($item['loan_request_id']);

            $item['insurance_rate'] = bcdiv($item['pre_insurance_amt'], $item['amount'], 4);
            $item['lending_rate'] = bcdiv($item['lending_rate'], 100, 4);
            $item['fines_rate'] = 0.0030;
            $rate = SettingRepayRate::getRateByChannl('10009', $item['period']);
            $item['month_insurance_rate'] = $rate['month_insurance_rate'];
            $item['repayment_rate'] = $rate['repayment_rate'];
            $item['user_id'] = $userId;
            empty($item['loan_id']) && $item['loan_id'] = 0;
            $item['bank_card_id'] = UserBankCard::where(['card_num' => $item['card_no']])->value('id') ?: 0;
            unset($item['card_no'], $item['product_code'], $item['loan_channel']);
            if(self::check($item['trans_id'])){
                continue;
            }else{
                $apply =LoanApply::create($item);
                if($item['loan_status'] == LoanApply::LOAN_STATUS_SUCCESS){
                    $list[] = $apply;
                }
            }
        }

        return $list ;
    }


    /**
     * Description:非晋商光大
     * Author: liuju
     * DateTime: 2019-03-12 15:24
     * @param $transList
     * @param $user
     * @param $userId
     * @param $term
     * @param $transIdList
     * @return bool
     */
    public static function three($transList, $user, $userId, $term,$transIdList)
    {
        $list = [];
        $data = DB::connection('transfer')->select("
        select 
       c.id trans_id,
       c.product_code,
       c.loan_channel,
       d.approve_amount as amount ,
       d.approve_amount  - ifnull(c.premium_amount,0)  as  arrival_account ,
			 ifnull(c.premium_amount,0)  as pre_insurance_amt ,
			 c.apply_term as period,
			 c.id as out_trade_id,
			 (case  when c.apply_status = '7' or c.apply_status = '8' or c.apply_status='9' then 2 when c.apply_status='10' then 3 end ) as loan_status ,
			 DATE_FORMAT(b.loan_time,'%Y-%m-%d %H:%i:%s')  as loan_time ,
		
        DATE_FORMAT(c.create_time,'%Y-%m-%d %H:%i:%s') as  created_at ,
				DATE_FORMAT(c.update_time,'%Y-%m-%d %H:%i:%s') as updated_at ,
				(select bank_card_no from  ws_account.account_user_card where id = c.loan_card_id ) as card_no ,
				c.ip,
				c.apply_rate as  lending_rate
from ws_loan.loan_order b,
		 ws_loan.loan_apply c,
		 ws_loan.loan_approve d
 where  c.id = b.apply_id
 and c.id = d.id
 and c.apply_status in ('7','8','9','10')
 and b.is_valid = 1
 and d.is_valid = 1
 and ((c.apply_status in ('7','8','9') and b.order_status = '2') or (c.apply_status = '10' and b.order_status = '3'))
 and d.is_valid = 1 and c.phone='" . $user->phone . "'
        ");

        $applyIdList = array_pluck($data, 'trans_id');
        $log = $applyIdList ? ApiLog::getResponse($applyIdList)->get()->toArray() : [];
        $moneyList = [];
        foreach ($log as $k => $value) {
            $key = $value['order_id'];
            $value = json_decode($value['response'], true);
            $moneyList[$key] = $value['data']['transMoneyList'];
        }
        foreach ($data as $item) {
            $item = (array)$item;
            if(in_array($item['trans_id'],$transIdList)){
                continue;
            }
            if(!self::$map){
                self::$map = [
                    'time'=> $item['created_at'],
                    'status'=>$item['loan_status']
                ];
            }
            if(self::$map && str_replace(['-',':'],'',$item['created_at'])){
                self::$map['status'] = $item['loan_status'];
            }
            foreach ($term as $info) {
                if ($info->product_code === $item['product_code'] && $info->loan_channel == $item['loan_channel'] && $info->term_no == $item['period']) {
                    $item['manage_rate'] = bcdiv(round($info->service_rate, 2), 100, 4);
                }
            }

            $item['amount'] = bcdiv($item['amount'], 100, 2);
            $item['arrival_account'] = bcdiv($item['arrival_account'], 100, 2);
            $item['pre_insurance_amt'] = bcdiv($item['pre_insurance_amt'], 100, 2);

            $item['trans_money_list'] = !empty($moneyList[$item['out_trade_id']]) ? $moneyList[$item['out_trade_id']] : '';
            if ($item['trans_money_list']) {
                foreach ($item['trans_money_list'] as $k1 => $v1) {
                    if ($v1['transType'] === '01') {
                        $item['pre_insurance_amt'] = $v1['transAmt'];
                    }
                    if ($v1['transType'] === '02') {
                        $item['performance_insurance'] = $v1['transAmt'];
                    }
                    if ($v1['transType'] === '03') {
                        $item['arrival_account'] = $v1['transAmt'];
                    }
                }
            }
            $item['loan_request_id'] = !empty($transList[$item['trans_id']]) ? $transList[$item['trans_id']] : '';

            $item['loan_request_id'] && self::updateLoanRequest($item['loan_request_id']);

            $item['insurance_rate'] = bcdiv($item['pre_insurance_amt'], $item['amount'], 4);
            $item['lending_rate'] = bcdiv($item['lending_rate'], 100, 4);
            $item['fines_rate'] = 0.0030;
            $rate = SettingRepayRate::getRateByChannl('', $item['period']);
            $item['month_insurance_rate'] = $rate['month_insurance_rate'];
            $item['repayment_rate'] = $rate['repayment_rate'];
            $item['user_id'] = $userId;
            empty($item['loan_id']) && $item['loan_id'] = 0;
            $item['bank_card_id'] = UserBankCard::where(['card_num' => $item['card_no']])->value('id') ?: 0;
            unset($item['card_no'], $item['product_code'], $item['loan_channel']);
            if(self::check($item['trans_id'])){
                continue;
            }else{
                $apply =LoanApply::create($item);
                if($item['loan_status'] == LoanApply::LOAN_STATUS_SUCCESS){
                    $list[] = $apply;
                }
            }
        }

        return $list ;
    }

    /**
     * Description:旧光大
     * Author: liuju
     * DateTime: 2019-03-12 15:30
     */
    public static function oldGd($transList, $user, $userId, $term,$transIdList)
    {
       $list = [];
       $data = DB::connection('transfer')->select("
      
select 
       c.id trans_id,
       c.product_code,
       c.loan_channel,
       d.approve_amount  amount ,
       e.user_receive_amount arrival_account ,
			 ifnull(e.user_premium,0) pre_insurance_amt ,
			  ifnull(e.fund_premium,0) performance_insurance ,
			 c.apply_term period,
			 c.id out_trade_id,
			 case  when c.apply_status = '7' or c.apply_status = '8' or c.apply_status='9' then 
              2
			 when c.apply_status='10' then 
			        3
			 end loan_status ,
			 DATE_FORMAT(b.loan_time,'%Y-%m-%d %H:%i:%s') loan_time ,
        DATE_FORMAT(c.create_time,'%Y-%m-%d %H:%i:%s') created_at ,
				DATE_FORMAT(c.update_time,'%Y-%m-%d %H:%i:%s') updated_at ,
				(select bank_card_no from  ws_account.account_user_card where id = c.loan_card_id ) as card_no,
				c.ip,
				c.apply_rate lending_rate
from ws_loan.loan_order b,
		 ws_loan.loan_apply c,
		 ws_loan.loan_approve d,
		 ws_xinliu.loan_order e
 where  c.id = b.apply_id
 and c.id = d.id
 and c.apply_status in ('7','8','9','10')
 and c.id = e.apply_id
 and b.order_status = '2'
 and b.is_valid = 1
 and c.loan_channel ='LCC201709190009'
 and d.is_valid = 1  and c.phone='".$user->phone."'
       ");

        $applyIdList = array_pluck($data, 'trans_id');
        $log = $applyIdList ? ApiLog::getResponse($applyIdList)->get()->toArray() : [];
        $moneyList = [];
        foreach ($log as $k => $value) {
            $key = $value['order_id'];
            $value = json_decode($value['response'], true);
            $moneyList[$key] = $value['data']['transMoneyList'];
        }
        foreach ($data as $key => $item) {
            $item = (array)$item;
            if(in_array($item['trans_id'],$transIdList)){
                continue;
            }
            if(!self::$map){
                self::$map = [
                    'time'=> $item['created_at'],
                    'status'=>$item['loan_status']
                ];
            }
            if(self::$map && str_replace(['-',':'],'',$item['created_at'])){
                self::$map['status'] = $item['loan_status'];
            }

            foreach ($term as $info) {
                if ($info->product_code === $item['product_code'] && $info->loan_channel == $item['loan_channel'] && $info->term_no == $item['period']) {
                    $item['manage_rate'] = bcdiv(round($info->service_rate, 2), 100, 4);
                }
            }
            $item['amount'] = bcdiv($item['amount'], 100, 2);

            $item['loan_request_id'] = !empty($transList[$item['trans_id']]) ? $transList[$item['trans_id']] : '';
            $item['loan_request_id'] && self::updateLoanRequest($item['loan_request_id']);

            $item['insurance_rate'] = bcdiv($item['pre_insurance_amt'], $item['amount'], 4);
            $item['lending_rate'] = bcdiv($item['lending_rate'], 100, 4);
            $item['fines_rate'] = 0.0030;
            $rate = SettingRepayRate::getRateByChannl('10009', $item['period']);
            $item['month_insurance_rate'] = $rate['month_insurance_rate'];
            $item['repayment_rate'] = $rate['repayment_rate'];
            $item['user_id'] = $userId;
            empty($item['loan_id']) && $item['loan_id'] = 0;
            $item['trans_money_list'] = !empty($moneyList[$item['out_trade_id']]) ? $moneyList[$item['out_trade_id']] : '';
            if ($item['trans_money_list']) {
                foreach ($item['trans_money_list'] as $k1 => $v1) {
                    if ($v1['transType'] === '01') {
                        $item['pre_insurance_amt'] = $v1['transAmt'];
                    }
                    if ($v1['transType'] === '02') {
                        $item['performance_insurance'] = $v1['transAmt'];
                    }
                    if ($v1['transType'] === '03') {
                        $item['arrival_account'] = $v1['transAmt'];
                    }
                }
            }
            $item['bank_card_id'] = UserBankCard::where(['card_num' => $item['card_no']])->value('id') ?: 0;
            unset($item['card_no'], $item['product_code'], $item['loan_channel']);
            if(self::check($item['trans_id'])){
                continue;
            }else{
                $apply =LoanApply::create($item);
                if($item['loan_status'] == LoanApply::LOAN_STATUS_SUCCESS){
                $list[] = $apply;
               }
            }

        }
        return $list ;
    }

    public static function check($transId)
    {
        return LoanApply::where('trans_id', $transId)->value('id');
    }


    public static function updateLoanRequest($loanRequestId)
    {
        return UserLoanRequest::where('id', $loanRequestId)
            ->where('status', '<>', UserLoanRequest::STATUS_SUCCESS)
            ->update([
                'status' => UserLoanRequest::STATUS_SUCCESS
            ]);
    }
}